import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;

//数据库管理器
class DBManager{
    private Connection conn;
    private Statement stmt;
    
    public DBManager(String url, String username, String password) 
    throws Exception{
        try{
            Class.forName("com.mysql.jdbc.Driver");
            
            this.conn = DriverManager.getConnection(url, username, password);
            
        }catch(Exception e){
            throw e;
        }
    }
    
    //封装结果集
    public void encapsolateResultSet(ArrayList<HashMap<String, Object>> allData, String sql)
    throws Exception{
        try{            
            //获取Statement
            stmt = conn.createStatement();
            
            //查询数据库，获取结果集
            ResultSet rs = stmt.executeQuery(sql);
            
            //获取元结果集
            ResultSetMetaData rsmd = rs.getMetaData();
            
            //获取结果表columns个数
            int numberOfColumns = rsmd.getColumnCount();
            
            //使用String[]保存字段名
            String[] columnNames = new String[numberOfColumns];
            for(int i = 0; i < columnNames.length; i++){
                columnNames[i] = rsmd.getColumnName(i + 1);
            }
            
            //使用allData封装结果集
            while(rs.next()){
                //String存储字段名， Object存储字段对象值
                HashMap<String, Object> rsMap = new HashMap<String, Object>();
                for(int i = 0; i < columnNames.length; i++){
                    //key
                    String key = columnNames[i];
                    //value
                    Object value = rs.getObject(columnNames[i]);
                    
                    rsMap.put(key, value);
                }
                allData.add(rsMap);
            }
            
        }catch(Exception e){
            throw e;
        }
    }
}